from django                   import template
from django.template          import TemplateSyntaxError
from sitepal.sitetheme.models import Theme,Layout

register = template.Library()

@register.tag(name="page")
def do_page(parser,token):
    contents = token.split_contents()
    if len(contents) == 1:
        tag_name = contents[0]
        title    = None
    elif len(contents) == 2:
        tag_name,title = contents
        if not (title[0] == title[-1] and title[0] in ('"', "'")):
            raise TemplateSyntaxError, "{0} tag's argument should be in quotes".format(tag_name)
        title = title[1:-1]
    else:
        raise TemplateSyntaxError,"{0} has an optional title argument".format(contents[0])
    nodelist = parser.parse(('endpage',))
    parser.delete_first_token()
    return PageNode(title,nodelist)

class PageNode(template.Node):
    def __init__(self,title,nodelist):
        self.title    = title or u''
        self.nodelist = nodelist

    def render(self,context):
        if self.title:
            context['title'] = self.title
        context['theme']  = theme  = Theme.objects.get_current()
        context['layout'] = layout = Layout.objects.get_current()
        output            = theme.safe(self.nodelist.render(context))
        page              = theme.render_page(content=output,
                                              layout=layout,
                                              title  =context.get('title'),
                                              request=context.get('request'))
        return theme.render_html(content=page,title=context.get('title'))

@register.tag(name="theme")
def do_theme(parser,token):
    try:
        tag_name = token.split_contents()
    except ValueError:
        raise TemplateSyntaxError,"{0} has no arguments".format(token.contents.split()[0])
    return ThemeNode()

class ThemeNode(template.Node):
    def __init__(self):
        pass

    def render(self,context):
        context['theme'] = Theme.objects.get_current()
        return ''

@register.tag(name="title")
def do_title(parser,token):
    try:
        tag_name,title = token.split_contents()
    except ValueError:
        raise TemplateSyntaxError,"{0} requires a title string".format(token.contents.split()[0])
    if not (title[0] == title[-1] and title[0] in ('"', "'")):
        raise TemplateSyntaxError, "{0} tag's argument should be in quotes".format(tag_name)
    return TitleNode(title[1:-1])

class TitleNode(template.Node):
    def __init__(self,title):
        self.title = title

    def render(self,context):
        context['title'] = title
        return ''

